package com.yys.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yys.springcloud.entities.CommonResult;
import com.yys.springcloud.entities.Payment;
import com.yys.springcloud.service.feign.PaymentFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @program: cloudalibaba2021
 * @description:
 * @author: Mr.Wu
 * @create: 2021-06-21 15:17
 **/
@RestController
@Slf4j
public class OrderController {
    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping("/consumer/payment/get/{id}")
    //这里添加SentinelResource注解,类似hystrix的command方式
    //异常会走fallback方法
    //限流降级等操作走blockHandler方法
    @SentinelResource(value = "getPaymentById",blockHandler = "blockHandler",fallback = "fallbackHandler")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        if(id == 2){
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }
        return paymentFeignService.getPaymentId(id);
    }


    //本例是blockHandler
    public CommonResult blockHandler(@PathVariable  Long id, BlockException blockException) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);
    }

    //fallback
    public CommonResult fallbackHandler(@PathVariable  Long id, Throwable e){
        Payment payment = new Payment(id, null);
        return new CommonResult<>(444,"程序错误fallback exception",payment);
    }
}
